<template>
  <section class="todoapp">
    <hm-header @handleAdd="handleAdd"></hm-header>
    <hm-main
      :list="showList"
      @destroy="del"
      @status="status"
      @handleChange="handleChange"
    ></hm-main>
    <hm-footer
      :list="list"
      @clear="clear"
      @status-event="arr = $event"
      :arr="arr"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [],
      arr: obj[location.hash] || "all",
    };
  },
  methods: {
    handleChange(id) {
      this.list.find((item) => item.id === id).isDone = !this.list.find(
        (item) => item.id === id
      ).isDone;
    },
    clear() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
    del(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    handleAdd(value) {
      this.list.unshift({
        id: +new Date(),
        name: value,
        isDone: false,
      });
    },
    status(value) {
      this.list.forEach((item) => (item.isDone = value));
    },
  },
  computed: {
    showList() {
      if (this.arr === "all") {
        return this.list;
      } else if (this.arr === "done") {
        return this.list.filter((item) => item.isDone === true);
      } else {
        return this.list.filter((item) => item.isDone === false);
      }
    },
  },
  watch: {
    list: {
      handler(newValue) {
        localStorage.setItem("list", JSON.stringify(newValue));
      },
      deep: true,
      immediate: true,
    },
  },
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
};
</script>

<style></style>
